<template>
  <div class="progress" ref="progress">
    <canvas class="progress__canvas" ref="canvas"></canvas>
    <div class="progress__inner">
      <div class="progress__percentage">{{percentage}}%</div>
      <div class="progress__tip">完成值</div>
    </div>
  </div>
</template>

<script>
    export default {
      name: 'Progress',
      data() {
        return {}
      },
      props: ['percentage'],
      methods:{
        drawProgress() {
          let getDevicePixelRatio = () => {
            return window.devicePixelRatio || 1;
          }
          let dpr = getDevicePixelRatio()
          
          let container = this.$refs.progress
          let canvas = this.$refs.canvas
          var ctx = canvas.getContext('2d')
          let containerW = container.clientWidth
          let containerH = container.clientHeight
          let canvasW = containerW * dpr
          let canvasH = containerH * dpr
  
          canvas.width = canvasW
          canvas.height = canvasH
          let centerX = canvasW / 2
          let centerY = canvasH / 2
          let lineW = 6 * dpr
          let r = canvasH / 2 - (lineW / 2)
          let startAngle = - Math.PI * 0.5
          let endAngle = startAngle + Math.PI * 2 * (parseInt(this.percentage) / 100 >= 1 ? 1 : parseInt(this.percentage) / 100)
          let dotR = lineW / 2
  
          ctx.beginPath()
          ctx.lineWidth = lineW
          ctx.strokeStyle = '#F0F0F0'
          ctx.arc(centerX, centerY, r, 0, Math.PI * 2, false)
          ctx.stroke()
  
          ctx.beginPath()
          ctx.lineWidth = lineW
          if (parseInt(this.percentage) > 50) {
            ctx.strokeStyle = '#419CFF'
          } else {
            ctx.strokeStyle = '#FC6F6F'
          }
          ctx.lineCap = 'round'
          ctx.arc(centerX, centerY, r, startAngle, endAngle, false)
          ctx.stroke()
          
          ctx.beginPath()
          ctx.fillStyle = 'rgba(0, 0, 0, .2)'
          ctx.arc(centerX + Math.cos(endAngle) * r , centerY + Math.sin(endAngle) * r ,  dotR, 0, Math.PI * 2, false)
          ctx.fill()
        }
      },
      mounted() {
        this.drawProgress()
      },
      watch: {
        percentage: {
          handler(newValue, oldValue) {
            this.drawProgress()
          },
          deep: true,
        }
      },
    }
</script>

<style lang="scss" scoped>
  .progress {
    width: 100%;
    height: 100%;
    position: relative;
    
    &__canvas {
      display: block;
      width: 100%;
      height: 100%;
    }
    
    &__inner {
      position: absolute;
      text-align: center;
      left: 0;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      line-height: 1.2;
    }
    
    &__percentage {
      font-size: 12px;
    }
    
    &__tip {
      font-size: 8px;
      color: #929292;
    }
  }
</style>
